/**
 * OpenAI 客户端示例
 * 演示如何使用 OpenAI 库与百炼 API 服务器通信
 */
const { OpenAI } = require('openai');

// 创建 OpenAI 客户端实例
const openai = new OpenAI({
  baseURL: 'http://localhost:3001/api/openai', // 指向我们的服务器
  apiKey: 'dummy-api-key', // 这个值可以是任意的，因为我们的服务器不验证它
});

// 聊天补全示例
async function chatExample() {
  try {
    console.log('Running chat completion example...');

    const response = await openai.chat.completions.create({
      model: 'bailian-default',
      messages: [
        { role: 'user', content: '你好，请介绍一下自己' }
      ],
      temperature: 0.7,
      max_tokens: 500
    });

    console.log('Chat response:');
    console.log(response.choices[0].message.content);
    console.log('\nFull response:');
    console.log(JSON.stringify(response, null, 2));
  } catch (error) {
    console.error('Chat completion error:', error);
  }
}

// 文本补全示例
async function completionExample() {
  try {
    console.log('Running text completion example...');

    const response = await openai.completions.create({
      model: 'bailian-default',
      prompt: '从前有座山',
      temperature: 0.7,
      max_tokens: 500
    });

    console.log('Completion response:');
    console.log(response.choices[0].text);
    console.log('\nFull response:');
    console.log(JSON.stringify(response, null, 2));
  } catch (error) {
    console.error('Text completion error:', error);
  }
}

// 图像分析示例（需要 Node.js 18+ 和 fs/promises）
async function imageAnalysisExample() {
  try {
    const fs = require('fs');
    const path = require('path');

    console.log('Running image analysis example...');

    // 读取图片文件（替换为你自己的图片路径）
    const imagePath = path.join(__dirname, 'example-image.jpg');

    // 检查文件是否存在
    if (!fs.existsSync(imagePath)) {
      console.error(`Image file not found: ${imagePath}`);
      console.error('Please place an image file named "example-image.jpg" in the examples directory');
      return;
    }

    // 读取图片并转换为 base64
    const imageBuffer = fs.readFileSync(imagePath);
    const base64Image = imageBuffer.toString('base64');

    // 调用 OpenAI API
    const response = await openai.chat.completions.create({
      model: 'bailian-default',
      messages: [
        {
          role: 'user',
          content: [
            { type: 'text', text: '请描述这张图片' },
            { type: 'image_url', image_url: { url: `data:image/jpeg;base64,${base64Image}` } }
          ]
        }
      ],
      max_tokens: 500
    });

    console.log('Image analysis response:');
    console.log(response.choices[0].message.content);
    console.log('\nFull response:');
    console.log(JSON.stringify(response, null, 2));
  } catch (error) {
    console.error('Image analysis error:', error);
  }
}

// 运行示例
async function runExamples() {
  // 聊天补全示例
  await chatExample();
  console.log('\n' + '-'.repeat(50) + '\n');

  // 文本补全示例
  await completionExample();
  console.log('\n' + '-'.repeat(50) + '\n');

  // 图像分析示例
  await imageAnalysisExample();
}

// 执行示例
runExamples();
